// Copyright 2007 the original author or authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package lichen.internal.security;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import lichen.entities.user.GrantedAuthorityBean;
import lichen.entities.user.User;
import lichen.services.UserService;

import org.apache.tapestry.services.Request;
import org.apache.tapestry.services.RequestFilter;
import org.apache.tapestry.services.RequestGlobals;
import org.apache.tapestry.services.RequestHandler;
import org.apache.tapestry.services.Response;

/**
 * 对安全进行控制的过滤器
 * @author Jun Tsai
 * @version $Revision$
 * @since 0.0.3
 */
public class SecurityContextFilter implements RequestFilter{

	/** request globals object **/
	private RequestGlobals _requestGlobals;
	/** user service **/
	private UserService _userService;
	
	public SecurityContextFilter(RequestGlobals requestGlobals,UserService userService){
		this._requestGlobals = requestGlobals;
		_userService = userService;
	}
	/**
	 * 
	 * @see org.apache.tapestry.services.RequestFilter#service(org.apache.tapestry.services.Request, org.apache.tapestry.services.Response, org.apache.tapestry.services.RequestHandler)
	 * @since 0.0.3
	 */
	public boolean service(Request request, Response response, RequestHandler handler) throws IOException {
		HttpServletRequest servletRequest = _requestGlobals.getHTTPServletRequest();
		
		User user = _userService.getCurrentUser();
		
		GrantedAuthorityBean[] authorities = null;
		if(user!=null )
			authorities=user.getAuthorities();
		
		SecuredHttpServletRequestWrapper delegateRequest = new SecuredHttpServletRequestWrapper(servletRequest,user,authorities);
		_requestGlobals.store(delegateRequest, _requestGlobals.getHTTPServletResponse());
		return handler.service(request, response);
		
	}
}
